package org.example.yiyu.exception;

import org.example.yiyu.response.CustomErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;

/**
 * 全局异常处理器，捕获并处理控制器层抛出的异常。
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常 CustomException
     * @param ex 自定义异常对象
     * @return 自定义的异常响应对象 ResponseEntity<CustomErrorResponse>
     */
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<CustomErrorResponse> handleCustomException(CustomException ex) {
        CustomErrorResponse error = new CustomErrorResponse();
        error.setTimestamp(LocalDateTime.now());
        error.setStatus(ex.getStatus());
        error.setError("Custom Exception");
        error.setMessage(ex.getMessage());
        return new ResponseEntity<>(error, HttpStatus.valueOf(ex.getStatus()));
    }

    /**
     * 处理其他未被捕获的异常 Exception
     * @param ex 异常对象
     * @return 统一的异常响应对象 ResponseEntity<CustomErrorResponse>
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<CustomErrorResponse> handleException(Exception ex) {
        CustomErrorResponse error = new CustomErrorResponse();
        error.setTimestamp(LocalDateTime.now());
        error.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        error.setError("Internal Server Error");
        error.setMessage(ex.getMessage());
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
